<template>
  <el-form ref="formRef" :model="formData">
  <el-descriptions class="mb-16" :column="column" :border="true">
    <el-descriptions-item
      v-for="(descItem, index) in descriptions"
      :key="index"
      :label="descItem.label"
      label-class-name="desc-label"
      :class-name="[column === 1 ? 'desc-content-1' : 'desc-content-2']"
    >
      <span v-if="readOnly">
        {{ descItem.content }}
      </span>
      <span v-else>
        <!-- 输入框 -->
        <el-form-item v-if="descItem.type === 'input'" :prop="descItem.filed" :rules="getRules(descItem.validator)">
          <el-input
            v-model="formData[descItem.filed]"
            :placeholder="descItem.placeholder"
          />
        </el-form-item>
        <!-- 只读输入框 -->
        <el-form-item v-if="descItem.type === 'readonlyInput'" :prop="descItem.filed" :rules="getRules(descItem.validator)">
          <el-input
            v-model="formData[descItem.filed]"
            :placeholder="descItem.placeholder"
            :readonly="true"
          />
        </el-form-item>
        <!-- 输入框 -->
        <el-form-item 
          v-if="descItem.type === 'textarea'"
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-input
            v-model="formData[descItem.filed]"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            :placeholder="descItem.placeholder"
          />
        </el-form-item>
        <!-- 人员选择 -->
        <el-form-item 
          v-if="descItem.type === 'userSelect'" 
          :prop="descItem.filed" 
          :rules="getRules('userSelect')"
          class="user-select-form-item"
        >
          <div class="flex">
            <el-input 
              v-model="formData[descItem.filed]" 
              :placeholder="descItem.placeholder"  
              :readonly="true"
            />
            <el-button 
              type="primary" 
              class="ml-8" 
              @click="openUserSelect(descItem.filed)"
            >选择用户</el-button>
          </div>
        </el-form-item>
        <!-- 下拉框 -->
        <el-form-item 
          v-if="descItem.type === 'select'"
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-select v-model="formData[descItem.filed]">
            <el-option
              v-for="item in descItem.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 多选下拉框 -->
        <el-form-item 
          v-if="descItem.type === 'multipleSelect'" 
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-select 
            v-model="selectedValuesMap[descItem.filed]"
            multiple
            :placeholder="'请选择' + descItem.label"
            @update:modelValue="(values) => handleSelectionChange(values, descItem.filed)"
          >
            <el-option
              v-for="item in descItem.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 日期选择器 -->
        <el-form-item 
          v-if="descItem.type === 'datePicker'"
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-date-picker
            style="width: 100%"
            v-model="formData[descItem.filed]"
            :placeholder="descItem.placeholder"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item 
          v-if="descItem.type === 'dateRangePicker'"
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-date-picker
            type="daterange"
            style="width: auto"
            v-model="formData[descItem.filed]"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <!-- 单选框组 -->
        <el-form-item 
          v-if="descItem.type === 'radioGroup'" 
          :prop="descItem.filed" 
          :rules="getRules(descItem.validator)"
          class="user-select-form-item"
        >
          <el-radio-group v-model="formData[descItem.filed]">
            <el-radio v-for="(item, index) in descItem.options" :key="index" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </span>
    </el-descriptions-item>
  </el-descriptions>
</el-form>
  <UserSelectDialog ref="userSelectDialog" :userSelectDialogProps="userSelectDialogProps" @updateSelectedUser="handleSelectedUser" />
</template>

<script lang="ts" setup>
import UserSelectDialog from '@/views/project/projectDetails/components/UserSelectDialog.vue'

onBeforeMount(() => {
  formData = props.descriptForm || {}
})
const formRef = ref()
// emit事件合集
const emit = defineEmits(['handleSelectedUser'])
const props = defineProps({
  // 描述组件动态数据
  descriptions: {
    type: Array,
    default: () => []
  },
  // 动态表单对象
  descriptForm: {
    type: Object,
    default: () => {}
  },
  // 是否为只读态
  readOnly: {
    type: Boolean,
    default: false
  },
  // 描述列数
  column: {
    type: Number,
    default: 2
  },
  // 用户角色列表参数
  userSelectDialogProps: {
    type: Object,
    default: () => {}
  }
})
const userSelectDialog = ref()
// 已选中人员对象
const selectedUserList = ref([])
// 动态表单数据体
let formData = reactive({})

// 用于存储每个下拉框的选中值
const selectedValuesMap = ref({})

// 监听 selectedValuesMap 的变化
watch(
  selectedValuesMap,
  (newValue) => {
    Object.keys(newValue).forEach(key => {
      const values = newValue[key];
      formData[key] = values.length > 0 
        ? values.sort((a, b) => a - b).join(',') 
        : ''
    });  },
  { deep: true }
);

// 监听每个下拉框对应的 formData 值变化
watch(
  () => props.descriptions,
  (descriptions) => {
    descriptions.forEach(item => {
      if (item.type === 'multipleSelect') {
        // 初始化 selectedValuesMap
        selectedValuesMap.value[item.filed] = props.descriptForm[item.filed]
        // 当 formData 中有值时，转换为数组
        if (formData[item.filed]) {
          selectedValuesMap.value[item.filed] = formData[item.filed].split(',').map(Number)
        }
      }
    })
  },
  { immediate: true, deep: true }
)

// 处理选中值变化的方法
const handleSelectionChange = (values, filed) => {
  formData[filed] = values.length > 0 
    ? values.sort((a, b) => a - b).join(',') 
    : ''
}

// 定义校验规则
const getRules = (validator) => {
  const rules = {}
  switch (validator) {
    case 'integer':
      rules.required = true
      rules.pattern = /^-\d+$/
      rules.message = '请输入整数'
      rules.trigger = 'blur'
      break
    case 'number':
      rules.required = true
      rules.pattern = /^-?\d+(\.\d+)?$/
      rules.message = '请输入数字'
      rules.trigger = 'blur'
      break
    case 'phone':
      rules.required = true
      rules.validator = (rule: any, value: string, callback: any) => {
        // 中国大陆手机号码（11位）
        const mobilePattern = /^1[3-9]\d{9}$/

        // 固定电话号码（包括3-4位区号）
        // 如：010-12345678 或 0571-12345678 或 02112345678
        const fixedLinePattern = /^(0\d{2,3}-?|\(0\d{2,3}\))[1-9]\d{6,7}$/

        // 国际电话号码格式（以+开头）
        const internationalPattern = /^\+\d{1,4}[-\s]?\d{6,14}$/

        if (mobilePattern.test(value) || fixedLinePattern.test(value) || internationalPattern.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的电话号码'))
        }
      }
      rules.trigger = 'blur'
      break
    case 'email':
      rules.required = true
      rules.type = 'email'
      // rules.pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      rules.message = '请输入正确的邮箱地址'
      rules.trigger = 'blur'
      break
    case 'optional':
      rules.required = false
      // rules.message = '该项为必填'
      // rules.trigger = 'blur'
      break
    case 'userSelect':
      rules.required = true
      rules.message = '请选择用户'
      rules.trigger = 'blur'
      break
    case 'required':
      rules.required = true
      rules.message = '该项为必填'
      rules.trigger = 'blur'
      break
    default:
      rules.required = true
      rules.message = '该项为必填'
      rules.trigger = 'blur'
      break
  }
  return rules // 直接返回 rules 对象
}

// 表单验证
const validateForm = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      if (valid) {
        resolve(true)
      } else {
        reject(false)
      }
    })
  })
}

// 打开选择用户模态框
const openUserSelect = (fieldName) => {
  userSelectDialog.value.userSelectVisible = true
  userSelectDialog.value.currentFieldName = fieldName;
}

// 选中人员事件
const handleSelectedUser = ({ userList, fieldName }) => {
  selectedUserList.value = userList
  formData[fieldName] = userList.map(user => user.nickname).join(', ');
  emit('handleSelectedUser', { userList, fieldName })
}
// 获取动态表单数据
const getFormData = () => {
  return formData
}

// 父组件使用ref调用的参数和方法
defineExpose({ formData, getFormData, validateForm })
</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');
::v-deep .desc-label {
  width: 210px;
}
// description为1列时content宽度
::v-deep .desc-content-1 {
  width: 900px;
}
// description为2列时content宽度
::v-deep .desc-content-2 {
  width: 320px;
}

.user-select-form-item {
  width: 100%;
  
  :deep(.el-form-item__content) {
    width: 100%;
    
    .flex {
      width: 100%;
      display: flex;
      
      .el-input {
        flex: 1;
      }
    }
  }
}
</style>